<script setup lang="ts">
import { getLodop } from '@/lib/lodop/LodopFuncs'
import JsBarcode from 'jsbarcode'
const visible = ref<boolean>(false)
const codes = ref<string[]>([])
function showDrawer(records) {
  codes.value = records.map((item) => `${item.warehouse_id}-${item.id}-${item.code}`)
  const len = codes.value.length
  visible.value = true
  nextTick(() => {
    for (let i = 0; i < len; i++) {
      JsBarcode(`#barcode-${i}`, codes.value[i], {
        format: 'CODE128'
      })
    }
  })
}
function onClose() {
  visible.value = false
}

function onPrint() {
  var LODOP = getLodop() // 获取Lodop对象
  if (!LODOP) {
    alert('请安装Lodop打印控件！')
    return
  }

  // 条形码的宽度和高度（单位：毫米）
  const barcodeWidthMm = 60 // 条形码宽度
  const barcodeHeightMm = 25 // 条形码高度

  LODOP.PRINT_INITA('0mm', '0mm', `60mm`, `40mm`, '')
  LODOP.SET_PRINT_PAGESIZE(1, '60mm', '40mm', '')

  // 将毫米转换为像素
  const mmToPx = (mm) => mm * 3.77952755906

  const barcodeWidthPx = mmToPx(barcodeWidthMm)
  const barcodeHeightPx = mmToPx(barcodeHeightMm)

  codes.value.forEach((code, index) => {
    const barcodeValue = code // 提取条形码值

    LODOP.ADD_PRINT_BARCODE(20, 0, barcodeWidthPx, barcodeHeightPx, '128Auto', barcodeValue) // 添加条形码
    LODOP.SET_PRINT_STYLEA(index, 'ShowBarText', 1) // 显示条形码下方的文字
    LODOP.SET_PRINT_STYLEA(index, 'FontSize', 12) // 设置文字字体大小
    LODOP.NewPageA()
  })

  LODOP.PREVIEW() // 预览打印
}

defineExpose({
  showDrawer,
  onClose
})
</script>
<template>
  <a-drawer title="库位码打印" :open="visible" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <div id="barcode-container">
      <canvas :id="`barcode-${index}`" v-for="(_, index) in codes" :key="index"></canvas>
    </div>
    <template #footer>
      <div class="flex justify-end">
        <a-button type="default" @click="onClose">关闭</a-button>
        <a-button type="primary" @click="onPrint" style="margin: 0 8px">打印</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<style scoped>
#barcode-container {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr; /* 只有一列 */
  grid-template-rows: repeat(auto-fill, minmax(50px, 1fr)); /* 每个条形码占一行 */
  gap: 10px;
}
</style>
